$(document).ready(function () {
    window.filesList = [];
    let table = $('#HonourTable').DataTable({
        "fnPreDrawCallback": function (oSettings) {
            var processing_div = $('#HonourTable_processing');
            processing_div.removeClass("card");
            processing_div.addClass("align-middle");

        },
        "ajax": {
            url: "/api/honour/list/",
            type: "GET",
            data: function(d) {
                d.honour_type = 'qualification';  // 添加静态参数 honour_type
            },
            dataSrc: "results"
        },
        "ordering": false,
        "serverSide": false,
        "paging": true,
        "lengthChange": false,
        "searching": true,
        "bProcessing": true,
        "dom": "<'row'<'col-sm-12 col-md-12'f>>" +
            "<'row'<'col-sm-12'tr>>" +
            "<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
        "language": {
            "sSearch": "",
            "sLengthMenu": "每页显示 _MENU_ 条记录",
            "sZeroRecords": "没有数据！",
            "sEmptyTable": "当前未查询到信息",
            "sInfo": "当前显示 _START_ 到 _END_ 条，共 _TOTAL_ 条记录",
            "sInfoEmpty": "显示0到0条记录",
            "sInfoFiltered": "数据表中共有 _MAX_ 条记录",
            "sProcessing": '<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>\n' +
                '<span class="sr-only">Loading...</span>',
            "sLoadingRecords": '',
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上页",
                "sNext": "下页",
                "sLast": "末页"
            }
        },
        "columns": [
            {
                "data": 'title'
            },
            {
                "data": {},
                "render": function (data) {
                    if (data['image_url']) {
                        return '<img class="img-fluid" style="width: 150px; height: 100px" src="' + data['image_url'] + '" alt="' + data['title'] + '">'
                    } else {
                        return ''
                    }
                }

            },
            {
                "data": 'award_date'
            },
            {
                "data": 'description'
            },
            {
                "data": {},
                "render": function (data) {
                    return '<a href="javascript:void(0);" style="text-decoration: none" onclick="edit_honour(\'' + data['title'] + '\',\'' + data['award_date'] + '\', \'' + data['description'] + '\', \'' + data['id'] + '\')">编辑</a>&nbsp;' +
                        '<a href="javascript:void(0);" style="text-decoration: none" onclick="delete_honour(\'' + data['id'] + '\')">删除</a>&nbsp;' +
                        '<a href="javascript:void(0)" data-toggle="modal" data-target="#uploadImage" onclick="uploadImageModal(\'' + data['id'] + '\')">上传图片</a>'
                }
            }
        ],
    });
    $('.dataTables_filter').attr("hidden", "hidden");
});

function submit_honour() {
    let title = $('#honour_name').val(),
        date = $('#honour_date').val(),
        description = $('#honour_description').val();
    if (title && date) {

        $.ajax({
            url: "/api/honour/create/",
            type: "POST",
            data: {
                title: title,
                award_date: date,
                description: description,
                honour_type: "qualification"
            },
            success: function () {
                let table = $('#HonourTable').DataTable();
                $('#AddModal').modal('hide');
                table.ajax.reload();
                $('#honour_name').val('');
                $('#honour_date').val('');
                $('#honour_description').val('');
            },
            error: function (e) {
                if (e.status === 400) {
                    alert("参数有误")
                }
            }
        })
    } else {
        alert("荣誉信息不能为空")
    }
}

function edit_honour(title, date, description, pk) {
    $('#edit_honour_name').val(title);
    $('#edit_honour_date').val(date);
    $('#edit_honour_description').val(description);
    $('#pk').val(pk);
    $('#EditModal').modal('show');
}

function sure_edit_honour() {
    let title = $('#edit_honour_name').val(),
        date = $('#edit_honour_date').val(),
        description = $('#edit_honour_description').val(),
        pk = $('#pk').val();

    $.ajax({
        url: "/api/honour/update/" + pk + "/",
        type: "PUT",
        data: {
            title: title,
            award_date: date,
            description: description,
            honour_type: "qualification"
        },
        success: function () {
            let table = $('#HonourTable').DataTable();
            $('#EditModal').modal('hide');
            table.ajax.reload()
        },
        error: function () {
            alert("更新失败")
        }
    })
}

function delete_honour(pk) {
    if (window.confirm("确认是否删除该荣誉")) {
        $.ajax({
            url: "/api/honour/delete/" + pk + "/",
            type: "DELETE",
            success: function () {
                let table = $('#HonourTable').DataTable();
                table.ajax.reload()
            },
            error: function () {
                alert("删除失败")
            }
        })
    } else {
        return false
    }
}

function uploadImageModal(id) {
    $('#product_id_span').text(id);
}

$('#uploadImg').change(function () {
    let files = this.files;
    let length = files.length;
    for (let i = 0; i < length; i++) {
        window.filesList.push(files[i]);
    }
    $('.selected-img').remove();
    let list_length = window.filesList.length;
    let fr = new FileReader();
    let img_id = "id_upload_img" + list_length - 1;
    $("#uploadImgBtn").before("<div class=\"selected-img\">\n" +
        "    <i class=\"iconfont icon-delete\" style=\"z-index: 999;background-color:rgba(255,255,255,.8);position: absolute;right: 3px;top: 3px;\" title=\"删除图片\" onclick=\"delete_img(this)\"></i>\n" +
        "    <img id=\"" + img_id + "\" src=\"\" alt=\"待选图片\" style=\"width: 160px;height: 100px;border-radius: 10px;\" onclick=\"show_big_img(this)\">\n" +
        "</div>");

    fr.readAsDataURL(window.filesList[list_length - 1]);
    fr.onload = function () {
        $('#' + img_id).attr("src", this.result)
    }
});

function upload_imgs() {
    let form_data = new FormData();
    let id = $('#product_id_span').text();
    let list_length = window.filesList.length;
    form_data.append('file', window.filesList[list_length - 1]);
    form_data.append('id', id);
    $.ajax({
        url: '/api/honour_img/upload/',
        type: 'POST',
        data: form_data,
        processData: false,
        contentType: false,
        success: function (callback) {
            alert("上传成功");
            window.location.reload()
        }
    });
}
